package com.app.hmst.main;

import java.util.ArrayList;
import java.util.List;

import android.annotation.SuppressLint;
import android.app.ActionBar.LayoutParams;
import android.content.DialogInterface;
import android.content.DialogInterface.OnCancelListener;
import android.graphics.Color;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.StrictMode;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.app.hmst.model.CategoryVO;
import com.app.hmst.model.HomestayInfoVO;
import com.app.hmst.model.HomestayVO;
import com.app.hmst.model.HouseInfoVO;
import com.app.hmst.model.IndicatorResultVO;
import com.app.hmst.model.IndicatorVO;
import com.app.hmst.model.SubCategoryVO;
import com.app.hmst.utils.GlobalVariable;
import com.app.hmst.utils.NumberUtils;
import com.jeremyfeinstein.slidingmenu.lib.SlidingMenu;
import com.roscopeco.ormdroid.Entity;

@SuppressLint({ "NewApi", "ValidFragment" }) public class EvaluateDetailFragment extends Fragment{
	private View v;
	private SlidingMenu _sm;
	private ImageView menu_icon,confirm_form;
	private LinearLayout contain_layuot;
	private int homeId,houseId;
	private HomestayInfoVO homestayInfoVO;
	private HouseInfoVO houseInfoVO;
	public EvaluateDetailFragment(SlidingMenu sm, int homeId, int houseId){
		this._sm = sm;
		this.homeId = homeId;
		this.houseId = houseId;
	}
	
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
		System.gc();
		StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
		StrictMode.setThreadPolicy(policy);
		
		v = inflater.inflate(R.layout.evaluate_detail_page,container, false);
		contain_layuot = (LinearLayout) v.findViewById(R.id.contain_layuot);
		confirm_form = (ImageView) v.findViewById(R.id.button1);
		confirm_form.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				//switchFragment(new ViewAllSummaryEvaluatePageFragment(_sm));
			}
		});
		
		/*Dynamically for adding text view part*/
		HomestayVO homestayVO = null;
		String evaluateText = "";
		String summaryText = "";
		String summaryMean = "";
		
		if(houseId==0){
			evaluateText = getString(R.string.homestay_header_home);
			summaryText = getString(R.string.homestay_summary_home);
			summaryMean = getString(R.string.homestay_summary_mean_home);
			homestayVO = Entity.query(HomestayVO.class).where("type").eq(GlobalVariable.TYPE_HOMESTAY).execute();
			homestayInfoVO = Entity.query(HomestayInfoVO.class).where("id").eq(homeId).execute();
		}else{
			evaluateText = getString(R.string.homestay_header_house);
			summaryText = getString(R.string.homestay_summary_house);
			summaryMean = getString(R.string.homestay_summary_mean_house);
			homestayVO = Entity.query(HomestayVO.class).where("type").eq(GlobalVariable.TYPE_HOUSE).execute();
			homestayInfoVO = Entity.query(HomestayInfoVO.class).where("id").eq(homeId).execute();
			houseInfoVO = Entity.query(HouseInfoVO.class).where("id").eq(houseId).execute();
		}
		
		
		//Add evaluate header name
		TextView evaluateName = new TextView(getActivity().getApplicationContext());
		evaluateName.setText(evaluateText);
		evaluateName.setTextSize(18);
		LinearLayout.LayoutParams txtHeaderParam = new LinearLayout.LayoutParams(630,LayoutParams.WRAP_CONTENT);
		evaluateName.setLayoutParams(txtHeaderParam);
		evaluateName.setTextColor(Color.parseColor("#0b3d91"));		
		contain_layuot.addView(evaluateName,0);
		
		
		
		double result = calculateScore(homestayVO,homeId,houseId);
        
        //Create Layout for result summary detail
      	RelativeLayout resultLayout = new RelativeLayout(getActivity().getApplicationContext());
      	RelativeLayout.LayoutParams resultLayoutParams = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT,100);      	
      	resultLayout.setBackgroundColor(Color.parseColor("#dad7d7"));
      	resultLayout.setLayoutParams(resultLayoutParams);
        
      	//Add result summary name
      	TextView resultSummaryName = new TextView(getActivity().getApplicationContext());
      	resultSummaryName.setText(summaryText);
      	resultSummaryName.setTextColor(Color.parseColor("#0b3d91"));
        RelativeLayout.LayoutParams resultSummaryNameLp = new RelativeLayout.LayoutParams(330,RelativeLayout.LayoutParams.WRAP_CONTENT);
        resultSummaryNameLp.setMargins(30, 0, 0, 0);
        resultSummaryNameLp.addRule(RelativeLayout.ALIGN_PARENT_LEFT);
        resultSummaryNameLp.addRule(RelativeLayout.CENTER_VERTICAL);
        resultSummaryName.setLayoutParams(resultSummaryNameLp);
        resultLayout.addView(resultSummaryName,0);
      	
        //Add result summary percentage
        TextView percSumResult = new TextView(getActivity().getApplicationContext());
        percSumResult.setText(result +" % ");
        percSumResult.setTextColor(Color.parseColor("#fd302b"));
        RelativeLayout.LayoutParams lpSumPerc = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT,RelativeLayout.LayoutParams.WRAP_CONTENT);        
        lpSumPerc.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
        lpSumPerc.addRule(RelativeLayout.CENTER_VERTICAL);
        lpSumPerc.setMargins(0, 0, 150, 0);      
        percSumResult.setLayoutParams(lpSumPerc);
        resultLayout.addView(percSumResult,0);
        contain_layuot.addView(resultLayout);
      	
        
        /*This part is not looping*/
        //Start Create layout for All Summary percentage        
        RelativeLayout percSummaryResult = new RelativeLayout(getActivity().getApplicationContext());
      	RelativeLayout.LayoutParams resultpercSummaryResultParams = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT,180);      	      	
      	percSummaryResult.setLayoutParams(resultpercSummaryResultParams);
        
      	//Add all summary percentage
      	TextView percSummaryResultTxt = new TextView(getActivity().getApplicationContext());
      	percSummaryResultTxt.setText(result +" % ");
      	percSummaryResultTxt.setTextSize(50);
      	percSummaryResultTxt.setTextColor(Color.parseColor("#fd302b"));
        RelativeLayout.LayoutParams lpPercSummaryResult = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT,RelativeLayout.LayoutParams.WRAP_CONTENT);        
        lpPercSummaryResult.addRule(RelativeLayout.CENTER_HORIZONTAL);
        lpPercSummaryResult.addRule(RelativeLayout.CENTER_VERTICAL);          
        percSummaryResultTxt.setLayoutParams(lpPercSummaryResult);
        percSummaryResult.addView(percSummaryResultTxt,0);
        
        //Add percentage of assessment point that pass
        TextView defaultPerc = new TextView(getActivity().getApplicationContext());
        defaultPerc.setText(summaryMean);
        defaultPerc.setTextSize(20);
        defaultPerc.setTextColor(Color.parseColor("#dad7d7"));     
        RelativeLayout.LayoutParams lpdefSummaryResult = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT,RelativeLayout.LayoutParams.WRAP_CONTENT);               
        lpdefSummaryResult.addRule(RelativeLayout.CENTER_HORIZONTAL);
        lpdefSummaryResult.setMargins(0, 150, 0, 0);
        defaultPerc.setLayoutParams(lpdefSummaryResult);
        percSummaryResult.addView(defaultPerc,0);

      	contain_layuot.addView(percSummaryResult);
        //End Create layout for All Summary percentage          
        
      	
      	
      	
		menu_icon = (ImageView) v.findViewById(R.id.imageView6);
		menu_icon.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				_sm.toggle();
			}
		});
		new Utils(getActivity()).onBackPressed(v, new ViewAllSummaryEvaluatePageFragment(_sm,homestayInfoVO),null);
		return v;
	}
	public double calculateScore(HomestayVO homestayVO,int homeStayId,int houseId){
		double result = 0.0;
		double score = 0.0;
		List<CategoryVO> catList = homestayVO.categories();
		if(catList!=null && catList.size()>0){
			int i=0;
			for(CategoryVO cat : catList){
				if("1".equals(cat.no)){
					result += calculateFormula(cat, homeStayId)*5;
					score = calculateFormula(cat, homeStayId)*5;
				}
				else if("2".equals(cat.no)){
					result += calculateHouseFormula(cat, homeStayId, houseId)*10;
					score = calculateHouseFormula(cat, homeStayId, houseId)*10;
				}else if("3".equals(cat.no)){
					result += calculateFormula(cat, homeStayId)*20;
					score = calculateHouseFormula(cat, homeStayId, houseId)*20;
				}else if("4".equals(cat.no)){
					result += calculateFormula(cat, homeStayId)*15;
					score = calculateHouseFormula(cat, homeStayId, houseId)*15;
				}else if("5".equals(cat.no)){
					result += calculateFormula(cat, homeStayId)*5;
					score = calculateHouseFormula(cat, homeStayId, houseId)*5;
				}else if("6".equals(cat.no)){
					result += calculateHouseFormula(cat, homeStayId, houseId)*15;
					score = calculateHouseFormula(cat, homeStayId, houseId)*15;
				}else if("7".equals(cat.no)){
					result += calculateFormula(cat, homeStayId)*10;
					score = calculateHouseFormula(cat, homeStayId, houseId)*10;
				}else if("8".equals(cat.no)){
					result += calculateFormula(cat, homeStayId)*10;
					score = calculateHouseFormula(cat, homeStayId, houseId)*10;
				}else if("9".equals(cat.no)){
					result += calculateFormula(cat, homeStayId)*10;
					score = calculateHouseFormula(cat, homeStayId, houseId)*10;
				}
				//Create Layout for result detail
				RelativeLayout reLayout = new RelativeLayout(getActivity().getApplicationContext());
				RelativeLayout.LayoutParams rlp = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT,60);		
				reLayout.setLayoutParams(rlp);
				
				//Add evaluate name
				TextView resultName = new TextView(getActivity().getApplicationContext());
				resultName.setText(cat.title);
				resultName.setTextColor(Color.parseColor("#0b3d91"));
		        RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT,RelativeLayout.LayoutParams.WRAP_CONTENT);
		        lp.setMargins(30, 0, 0, 0);
		        lp.addRule(RelativeLayout.ALIGN_PARENT_LEFT);
		        lp.addRule(RelativeLayout.CENTER_VERTICAL);
		        resultName.setLayoutParams(lp);
		        reLayout.addView(resultName,0);
		        
		        //Add percent result for that evaluate name
		        TextView percResult = new TextView(getActivity().getApplicationContext());
		        percResult.setText(NumberUtils.round(score, 2)+" % ");
		        percResult.setTextColor(Color.parseColor("#fd302b"));
		        RelativeLayout.LayoutParams lpPerc = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT,RelativeLayout.LayoutParams.WRAP_CONTENT);        
		        lpPerc.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
		        lpPerc.addRule(RelativeLayout.CENTER_VERTICAL);
		        lpPerc.setMargins(0, 0, 150, 0);      
		        percResult.setLayoutParams(lpPerc);
		        reLayout.addView(percResult,0);
		        
		        //Add edit button for that evaluate name
		        final ImageView editBtn = new ImageView(getActivity().getApplicationContext());
		        editBtn.setImageDrawable(getResources().getDrawable(R.drawable.edit_btn_default));
		        editBtn.setTag(i);
		        RelativeLayout.LayoutParams lpBtn = new RelativeLayout.LayoutParams(100,RelativeLayout.LayoutParams.WRAP_CONTENT);
		        lpBtn.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
		        lpBtn.addRule(RelativeLayout.CENTER_VERTICAL);
		        lpBtn.setMargins(0, 0, 20, 0);
		        editBtn.setLayoutParams(lpBtn);
		        
		        final boolean isHomeStay = houseId==0;
		        
		        editBtn.setOnClickListener(new OnClickListener() {
					
					@Override
					public void onClick(View v) {
						int catCouunt = (Integer) editBtn.getTag();
						if(isHomeStay){
						switchFragment(new EvaluateFormFragment(_sm, homestayInfoVO,isHomeStay,catCouunt));
						}else{
						switchFragment(new EvaluateFormFragment(_sm, homestayInfoVO,houseInfoVO,isHomeStay,catCouunt));	
						}
					}
				});
		        
		        
		        reLayout.addView(editBtn,0);
		        contain_layuot.addView(reLayout);
		        i++;
			}
		}
		return NumberUtils.round(result, 2);
	}
	public double calculateFormula(CategoryVO cat,int homeStayId){
		double result =0.0;
		double indCount = 0;
		double y = 0;
		double na = 0;
		List<SubCategoryVO> subList = cat.subCategories();
		if(subList!=null && subList.size()>0){
			for(SubCategoryVO sub : subList){
				List<IndicatorVO> indList = sub.indicators();
				if(indList!=null && indList.size()>0){
					indCount += indList.size();
				}
			}
			List<IndicatorResultVO> indResultList = Entity.query(IndicatorResultVO.class).where("categoryId").eq(cat.id)
					.and("homeId").eq(homeStayId).executeMulti();
			if(indResultList!=null && indResultList.size()>0){
				for(IndicatorResultVO resultVO : indResultList){
					if("0".equals(resultVO.result)){
						y++;
					}else if("2".equals(resultVO.result)){
						na++;
					}
					
				}
				
			}
			result = y/(indCount-na);
		}
		
		return result;
	}
	public double calculateHouseFormula(CategoryVO cat,int homeStayId,int houseId){
		double result =0.0;
		double indCount = 0;
		double y = 0;
		double na = 0;
		List<SubCategoryVO> subList = cat.subCategories();
		if(subList!=null && subList.size()>0){
			for(SubCategoryVO sub : subList){
				List<IndicatorVO> indList = sub.indicators();
				if(indList!=null && indList.size()>0){
					indCount += indList.size();
				}
			}
			List<IndicatorResultVO> indResultList = Entity.query(IndicatorResultVO.class).where("categoryId").eq(cat.id)
					.and("homeId").eq(homeStayId).and("houseId").eq(houseId).executeMulti();
			if(indResultList!=null && indResultList.size()>0){
				for(IndicatorResultVO resultVO : indResultList){
					if("0".equals(resultVO.result)){
						y++;
					}else if("2".equals(resultVO.result)){
						na++;
					}
					
				}
				
			}
			result = y/(indCount-na);
		}
		
		return result;
	}
	private void switchFragment(Fragment fragment) {
		if (getActivity() == null)
			return;

		if (getActivity() instanceof HomeStayMainActivity) {
			HomeStayMainActivity fca = (HomeStayMainActivity) getActivity();
			fca.switchContent(fragment);
		}
	}
	public class InitAndLoadData extends AsyncTask<String, Void, List<String>> implements OnCancelListener{
		ProgressHUD mProgressHUD;
		
    	@Override
    	protected void onPreExecute() {
        	mProgressHUD = ProgressHUD.show(getActivity(),"Loading Content...", true,true,this);
    		super.onPreExecute();
    	}
		@Override
		protected List<String> doInBackground(String... params) {
			// TODO Auto-generated method stub			
			List<String> list = new ArrayList<String>();
			list.add("000");
			return list;
		}
		
		@Override
		protected void onPostExecute(List<String> result) {
			super.onPostExecute(result);
			if (result != null) {
				
				mProgressHUD.dismiss();
			} else {
				mProgressHUD.dismiss();
			}
			
		}
		@Override
		public void onCancel(DialogInterface dialog) {
			// TODO Auto-generated method stub
			mProgressHUD.dismiss();
		}


	}
}
